package cn.hf.mychat.constanst;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

import java.math.BigInteger;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * String工具类
 * @author Roskin
 *
 */
public class StringUtils {
	/**
	 * 首字母变小写
	 * @param str 需转换的字符串
	 * @return
	 */
	public static String firstCharToLowerCase(String str){
		char firstChar = str.charAt(0);
		if(firstChar>='A'&&firstChar<='Z'){
			char[] arr = str.toCharArray();
			arr[0] += ('a'-'Z');
			return new String(arr);		
		}
		return str;
	}
	/**
	 * 首字母变大写
	 * @param str	需转换的字符串
	 * @return
	 */
	public static String firstCharToUpperCase(String str){
		char firstChar = str.charAt(0);
		if(firstChar>='a'&&firstChar<='z'){
			char[] arr = str.toCharArray();
			arr[0] -= ('a'-'Z');
			return new String(arr);
		}
		return str;
	}
	/**
	 * 字符串为 null 或者内部字符全部为 ' ' '\t' '\n' '\r' 这四类字符时返回 true
	 * @param str
	 * @return
	 */
	public static boolean isNull(String str){
		if(str==null) return true;
		if("null".equals(str)) return true;
		int length = str.length();
		if(length==0) return true;
		for(int i=0;i<length;i++){
			switch (str.charAt(i)) {
				case ' ':
				case '\t':
				case '\n':
				case '\r':
					break;
	
				default:
					return false;
			}
		}
		return true;
	}
	
	/**
	 * 判断字符串不为 null
	 * @param str 判断的字符串
	 * @return
	 */
	public static boolean isNotNull(String str){
		return !isNull(str);
	}
	/**
	 * 判断多个字符串不为 null
	 * @param strings 多个String字符串
	 * @return
	 */
	public static boolean isNotNull(String... strings){
		if(strings==null) return false;
		for(String str:strings){
			if(isNull(str))
				return false;
		}
		return true;
	}
	/**
	 * 将带下划线的字符串转换为驼峰式
	 * @param str
	 * @return
	 */
	public static String toCamelCase(String str){
		if(str.indexOf('_')==-1) return str;
		str = str.toLowerCase();
		char[] fromArray = str.toCharArray();
		char[] toArray = new char[fromArray.length];
		int i=0;
		for(int j=0;j<fromArray.length;j++){
			if(fromArray[j]=='_'){
				// 当前字符为下划线时，将指针后移一位，将紧随下划线后面一个字符转成大写并存放
				j++;
				if(j<fromArray.length){
					toArray[i++] = Character.toUpperCase(fromArray[j]);
				}
			}else{
				toArray[i++] = fromArray[j];
			}
		}
		return new String(toArray,0,i);
	}
	/**
	 * 驼峰转下划线格式
	 * @param str
	 * @return
	 */
	public static String camelCaseToUnderLine(String str) {
		Pattern pattern = Pattern.compile("[A-Z]");
		Matcher matcher = pattern.matcher(str);
		StringBuffer sb = new StringBuffer();
		while(matcher.find()){  
            matcher.appendReplacement(sb, "_"+matcher.group(0).toLowerCase());  
        }
		matcher.appendTail(sb);  
        return sb.toString();  
	}
	/**
	 * 将String数组拼接成一个字符串，不带分隔符
	 * @param strings
	 * @return
	 */
	public static String join(String[] strings){
		StringBuffer sb = new StringBuffer();
		for(String str:strings){
			sb.append(str);
		}
		return sb.toString();
	}
	/**
	 * 将String数组拼接成一个字符串，以分隔符分隔
	 * @param strings
	 * @param separator 分隔符
	 * @return
	 */
	public static String join(String[] strings,String separator){
		StringBuffer sb = new StringBuffer();
		for(int i=0;i<strings.length;i++){
			sb.append(strings[i]);
			if(i>0&&i<strings.length-1){
				sb.append(separator);
			}
		}
		return sb.toString();
	}
	
	
	/**
	 * 比较两个字符串是否相等
	 * @param a
	 * @param b
	 * @return
	 */
	public static boolean slowEquals(String a,String b){
		byte[] aBytes = (a!=null?a.getBytes():null);
		byte[] bBytes = (b!=null?b.getBytes():null);
		return ByteUtils.slowEquals(aBytes, bBytes);
	}
	/**
	 * 生成UUID
	 * @return
	 */
	public static String getRandomUUID(){
		return UUID.randomUUID().toString().replace("-", "");
	}
	/**
	 * 根据模板及参数获得内容
	 * @param tempalte	模板内容
	 * @param parameters	模板参数
	 * @return
	 */
	public static String parseContent(String tempalte, Map<String,String> parameters){  
        Pattern p = Pattern.compile("(\\{([a-zA-Z]+)\\})");  
        Matcher m = p.matcher(tempalte);  
        StringBuffer stringBuffer = new StringBuffer();  
        while (m.find()){  
            String key = m.group(2);  
            String value = null;  
            if (parameters.containsKey(key)){  
                value = parameters.get(key);  
            }  
            value = (value == null) ? "" : value;  
            m.appendReplacement(stringBuffer,value);  
        }  
        m.appendTail(stringBuffer);  
        return stringBuffer.toString();  
    } 
	/**
	 * 数字验证
	 * @param str	待验证的字符串
	 * @return
	 */
	public static boolean isDigital(String str) {  
        return  StringUtils.isNull(str) ? false : str.matches("^[0-9]*$");  
    }  
	/**
	 * 将字符数组转为整型数组
	 * @param str 字符串
	 * @return
	 * @throws NumberFormatException
	 */
	public static int[] converCharToInt(String str) throws NumberFormatException { 
		char c[] = str.toCharArray();
		if(isNull(str)) return null;
        int[] a = new int[c.length];  
        int k = 0;  
        for (char temp : c) {  
            a[k++] = Integer.parseInt(String.valueOf(temp));  
        }  
        return a;  
    } 
	/**
	 * 根据当前时间生成ID字符串（纳秒）
	 * @return
	 */
	public static String id() {
		return new BeanX().encode(BigInteger.valueOf(System.nanoTime()));
	}
	/**
	 * 随机生成字符串
	 * @param num	生成字符串的个数
	 * @return
	 */
	public static String code(int num) {
		Random random = new Random();
		StringBuilder sb = new StringBuilder();
		for(int i=0;i<num;i++) {
			sb.append(random.nextInt(10));
		}
		return sb.toString();
	}
	/**
	 * Email格式验证
	 * @param emailStr
	 * @return
	 */
	public static boolean isEmail(String emailStr) {
		return emailStr.matches(".+@[\\d|\\w]+\\.[\\d|\\w]+(\\.[\\d|\\w]+)*");
	}
	/**
	 * 格式化模糊查询
	 * @param str
	 * @return
	 */
	public static String formatLike(String str){
        if(isNotNull(str)){
            return "%"+str+"%";
        }else{
            return null;
        }
    }
	
	/**
	 * 根据汉字得到全拼
	 * @param src	汉字
	 * @return
	 */
	public static String getPingYin(String src) {
        char[] t1 = null;
        t1 = src.toCharArray();
        String[] t2 = new String[t1.length];
        HanyuPinyinOutputFormat t3 = new HanyuPinyinOutputFormat();
        t3.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        t3.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        t3.setVCharType(HanyuPinyinVCharType.WITH_V);
        String t4 = "";
        int t0 = t1.length;
        try {
            for (int i = 0; i < t0; i++) {
                // 判断是否为汉字字符
                if (Character.toString(t1[i]).matches("[\\u4E00-\\u9FA5]+")) {
                    t2 = PinyinHelper.toHanyuPinyinStringArray(t1[i], t3);
                    t4 += t2[0];
                } else {
                    t4 += Character.toString(t1[i]);
                }
            }
            return t4;
        } catch (BadHanyuPinyinOutputFormatCombination e1) {
            e1.printStackTrace();
        }
        return t4;
    }
	/**
	 * 得到中文首字母
	 * @param str
	 * @return
	 */
	public static String getPinYinHeadChar(String str) {
        String convert = "";
        for (int j = 0; j < str.length(); j++) {
            char word = str.charAt(j);
            String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word);
            if (pinyinArray != null) {
                convert += pinyinArray[0].charAt(0);
            } else {
                convert += word;
            }
        }
        return convert;
    }
	/**
	 * 将字符串转移为ASCII码
	 * @param cnStr
	 * @return
	 */
	public static String getCnASCII(String cnStr) {
        StringBuffer strBuf = new StringBuffer();
        byte[] bGBK = cnStr.getBytes();
        for (int i = 0; i < bGBK.length; i++) {
            strBuf.append(Integer.toHexString(bGBK[i] & 0xff));
        }
        return strBuf.toString();
    }

}
